package ru.pb.game.avto_save;

import org.apache.log4j.Logger;

import ru.pb.game.controllers.AuthServerController;
import ru.pb.game.network.GNetworkEngine;
import ru.pb.game.network.threading.ThreadPoolManager;
import ru.pb.game.objects.model.players.Player;
import ru.pb.game.objects.storage.ObjectsStorage;
import ru.pb.global.dbc.DatabaseFactory;

/**
 * @author: Felixx
 */
public class GameShutdownThread extends Thread
{
	@Override
	public void run()
	{
		synchronized(this)
		{
			AutoSaveRunner.getInstance().shutdown();

			try
			{
				disconnectAllPlayers();
				try
				{
					Thread.sleep(2000);
				}
				catch(InterruptedException ignored)
				{}
			}
			finally
			{
				try
				{
					AuthServerController.getInstance().shutdown();

					GNetworkEngine.getInstance().unbindANDdisconnect();

					ThreadPoolManager.getInstance().shutdown();

					DatabaseFactory.getInstance().shutdown();
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	private void disconnectAllPlayers()
	{
		Logger.getLogger(GameShutdownThread.class).info("Disconnecting all players...");
		for(Player player : ObjectsStorage.getInstance().getAllPlayersForIterable())
		{
			try
			{
				Logger.getLogger(GameShutdownThread.class).info("Disconnect player: " + player.getName());
				player.logout(true, false, false); // Logout player
			}
			catch(Throwable t)
			{
				Logger.getLogger(GameShutdownThread.class).error("Error while disconnect player: " + player.getName());
				t.printStackTrace();
			}
		}

		try
		{
			Thread.sleep(1000);
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
	}
}